import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import { Card, Modal, Button, message } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import LayerModel from '../components/layerModel';
import moment from 'moment';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  listData: state.basicCommands.pageData,
  loading: state.loading.effects['basicCommands/getFetchPage'],
  permissions: state?.menu?.permissions,
});

class index extends PureComponent {
  state = {
    rightQuery: {},
  };
  layerRef = React.createRef();
  payloadUrl = '/remote/config/base/command/page';
  payloadType = 'basicCommands/getFetchPage';

  componentDidMount() {
    this.getList();
  }

  postDelete = (record: any, close: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/remote/config/base/command/delete/${record.sid}` },
      callback: res => {
        // 关闭弹层
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          this.getList();
          // 提示
          message.success('删除成功');
        }
      },
    });
  };

  getList = () => {
    // 获取数据
    const { rightQuery } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: this.payloadType,
      payload: { url: this.payloadUrl, ...rightQuery },
    });
  };

  // 新增
  rightNewAdd = () => {
    this.layerRef?.current?.setInitVal(`新增命令`);
  };
  // 保存
  onchange = async (obj, close) => {
    console.log(obj);
    // 提交
    const { dispatch } = this.props;
    const { sid, commandCode, commandName, delayStatus, remark } = obj;
    const params = {
      commandCode,
      commandName,
      delayStatus,
      remark,
    };
    Object.assign(params, sid ? { sid } : {});
    const type = sid ? 'edit' : 'save';
    dispatch({
      type: 'modelConfig/postObjWithRes',
      payload: { url: `/remote/config/base/command/${type}`, ...params },
      callback: res => {
        if (res.statusCode !== '0') {
          close(true);
          return false;
        }
        // 关闭
        close();
        // 刷新数据
        this.getList();
        // 提示
        message.success(`${sid ? '更新' : '新增'}成功`);
      },
    });
  };

  render() {
    const { rightQuery } = this.state;
    const {
      loading,
      location: { pathname = '/' },
      listData: { list, pagination },
      permissions,
    } = this.props;

    const searchItems = [
      {
        type: 'input',
        title: `命令名称`,
        key: 'commandName',
      },
      {
        type: 'input',
        title: `命令编号`,
        key: 'commandCode',
      },
    ];
    const rightColumns = [
      {
        title: `基础命令名称`,
        dataIndex: 'commandName',
      },
      {
        title: `基础命令编号`,
        dataIndex: 'commandCode',
      },
      {
        title: `状态延迟（statusDelay）`,
        dataIndex: 'delayStatus',
      },
      {
        title: `备注`,
        dataIndex: 'remark',
      },
      {
        title: `操作人`,
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: `创建时间`,
        dataIndex: 'createDate',
        render: (txt: string) => moment(txt).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 140,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'detail',
              auth: 'basicCommands_edit',
              onConfirm: () => {
                // 获取数据
                // 打开弹层传值
                this.layerRef?.current?.setInitVal('编辑命令', record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'basicCommands_delete',
              // Popconfirm: true,
              // message: '是否确定删除？',
              onConfirm: () => {
                let confirmLoading = false;
                Modal.confirm({
                  title: '删除',
                  content: (
                    <>
                      <p>确定要删除当前命令吗？</p>
                    </>
                  ),
                  wrapClassName: 'layer-model-box',
                  icon: <ExclamationCircleOutlined />,
                  onOk: close => {
                    // 如果为重复点击
                    if (confirmLoading) {
                      return false;
                    }
                    confirmLoading = true;
                    // 点击删除请求接口
                    this.postDelete(record, close);
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{!pagination ? 0 : pagination.total}&nbsp;条</span>,
    };
    const rightTable = {
      columns: rightColumns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };

    const layerColumns = [
      {
        type: 'input',
        formItem: {
          name: 'commandName',
          label: '基础命令名称',
          rules: [{ required: true, message: '请输入基础命令名称' }],
        },
        label: {
          placeholder: '请输入基础命令名称',
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'commandCode',
          label: '基础命令编号',
          rules: [{ required: true, message: '请输入基础命令编号' }],
        },
        label: {
          placeholder: '请输入基础命令编号',
          maxLength: 50,
        },
      },
      {
        type: 'inputNumber',
        formItem: {
          name: 'delayStatus',
          label: (
            <span>
              状态延迟
              <br />
              （statusDelay）
            </span>
          ),
          className: 'layer-status-delay',
        },
        label: {
          placeholder: '请输入状态延迟',
          addonAfter: '秒',
          max: 999999999,
        },
      },
      {
        type: 'textArea',
        formItem: {
          name: 'remark',
          label: '备注',
        },
        label: {
          placeholder: '请输入备注',
        },
      },
    ];

    return (
      <div>
        <Card>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl }}
            saveFormValues={(val: any) => this.setState({ rightQuery: { ...rightQuery, ...val } })}
            handleFormReset={() => this.setState({ rightQuery: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {permissions.includes(`${pathname}/basicCommands_add`) && (
            <div className="my_newItem">
              <Button type="primary" onClick={this.rightNewAdd} icon={<PlusOutlined />}>
                新增命令
              </Button>
            </div>
          )}
          <PateoTable
            extraHandle={true}
            tableProps={rightTable}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl }}
            formValues={rightQuery}
            currentName="pageNo"
          />
        </Card>
        <LayerModel
          ref={this.layerRef}
          onChange={this.onchange}
          columns={layerColumns}
        ></LayerModel>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
